from django.shortcuts import render, redirect
from app01 import models
from app01.utils.pageination import Pagination
from app01.utils.form import user_modelform


def user_list(request):
    """用户管理"""
    # 获取所有用户列表
    queryset = models.UserInfo.objects.all()
    page_object = Pagination(request, queryset, page_size=2)
    context = {
        'queryset': page_object.page_queryset,
        'page_str': page_object.html()
    }
    return render(request, 'user_list.html', context)


def user_add(request):
    """添加用户（原始方式）"""
    if request.method == 'GET':
        context = {
            'gender_choices': models.UserInfo.gender_choices,
            'depart_list': models.Department.objects.all()
        }
        return render(request, 'user_add.html', context)
    # 获取用户提交的数据
    user = request.POST.get('user')
    pwd = request.POST.get('pwd')
    age = request.POST.get('age')
    account = request.POST.get('ac')
    ctime = request.POST.get('ctime')
    gender_id = request.POST.get('gd')
    depart_id = request.POST.get('dp')
    # 添加到数据库中
    models.UserInfo.objects.create(name=user, password=pwd, age=age, account=account, create_time=ctime,
                                   gender=gender_id, depart_id=depart_id)
    # 返回到用户列表页面
    return redirect('/user/list/')


def user_model_form_add(request):
    """添加用户"""
    if request.method == 'GET':
        form = user_modelform()
        return render(request, 'user_modelform_add.html', {'form': form})
    # 用户post提交的数据，数据校验
    form = user_modelform(data=request.POST)
    if form.is_valid():
        # 如果数据符合，则要保存到数据库
        # print(form.changed_data)
        # models.UserInfo.objects.create(..)
        form.save()
        return redirect('/user/list/')
    # 校验失败(在页面上显示错误信息)
    # print(form.errors)
    return render(request, 'user_modelform_add.html', {'form': form})


def user_edit(request, nid):
    if request.method == 'GET':
        # 根据id去数据库获取要编辑的那一行的数据(对象)
        row_objects = models.UserInfo.objects.filter(id=nid).first()
        form = user_modelform(instance=row_objects)
        return render(request, 'user_edit.html', {'form': form})
    row_objects = models.UserInfo.objects.filter(id=nid).first()
    form = user_modelform(data=request.POST, instance=row_objects)
    if form.is_valid():
        # 默认保存的是用户输入的数据
        # form.instance.字段名=值
        form.save()
        return redirect('/user/list/')
    return render(request, 'user_edit.html', {'form': form})


def user_delete(request, nid):
    models.UserInfo.objects.filter(id=nid).delete()
    return redirect('/user/list/')

